package com.im.web.session;

import com.im.web.core.QueryUtils;
import com.im.web.core.model.QUserInfo;
import com.im.web.core.model.UserInfo;
import com.im.web.core.repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Optional;

import static com.im.common.Constants.IS_EXIST;

/**
 * @author gongym
 * @date 2018/11/16 10:59
 */
@Service
public class UserInfoSession {
  private UserInfoRepository userInfoRepository;

  @Autowired
  public UserInfoSession(UserInfoRepository userInfoRepository) {
    this.userInfoRepository = userInfoRepository;
  }

  @SuppressWarnings("Duplicates")
  public Long getCurrentUser() {
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    QUserInfo qUserInfo = QUserInfo.userInfo;
    QueryUtils queryUtils = new QueryUtils();
    queryUtils
        .putExpression(qUserInfo.delFlag.eq(IS_EXIST))
        .putExpression(qUserInfo.account.eq(username));
    Optional<UserInfo> userInfoOptional = userInfoRepository.findOne(queryUtils.buildQuery());
    UserInfo userInfo = userInfoOptional.orElse(null);
    Assert.notNull(userInfo, "用户信息为空，用户未登录");
    return userInfo.getId();
  }
}
